/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Zeshui Xu<i@xuzeshui.com>
 * Created Time: 2016-03-17 13:58:50
 * Last Modified: 2017-08-01 10:12:31
 * File Name: rpc/client/ip/iplocation.go
 * Description:
 */
package ip

// package main

import (
	"crypto/tls"
	"fmt"

	"doubimeizhi.com/utility"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
)

var (
	openapihost   string = "openapi.qkier.com"
	openapiAppkey string = "140a6d51d67c477e83cd91a241678824"
	openapiSecret string = "88366f9fad954828a194f3232a78a471"
)

type IPLocationResult struct {
	CountryId  string `json:"country_id"`
	Country    string `json:"country"`
	ISPId      string `json:"isp_id"`
	ISP        string `json:"isp"`
	ProvinceId string `json:"province_id"`
	Province   string `json:"province"`
	CityId     string `json:"city_id"`
	City       string `json:"city"`
	CountyId   string `json:"county_id"`
	County     string `json:"county"`
	AreaId     string `json:"area_id"`
	Area       string `json:"area"`
	RegionCode string `json:"region_code"`
}

type IPLocationResp struct {
	Code int               `json:"code"`
	Msg  string            `json:"msg"`
	Data *IPLocationResult `json:"data"`
}

func IPLocation(clientIP string) *IPLocationResult {
	nusb := utility.NewURLSignBuilder(openapiAppkey, openapiSecret, fmt.Sprintf("https://%s/v1/ip/location", openapihost))
	nusb.SetURLParam("ip", clientIP)
	reqURL := nusb.BuildURL()
	// reqURL := fmt.Sprintf("http://openapi.qkier.com/v1/ip/location?appkey=140a6d51d67c477e83cd91a241678824&ip=%s", clientIP)
	b := httplib.Get(reqURL)
	b.SetHost(openapihost)
	b.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
	ipdata := &IPLocationResp{}
	if err := b.ToJSON(ipdata); err != nil {
		return nil
	}
	if ipdata.Code != 0 {
		return nil
	}
	return ipdata.Data
}

func init() {
	openapihost = beego.AppConfig.DefaultString("backsvr::openapi_host", "openapi.qkier.com")
	openapiAppkey = beego.AppConfig.DefaultString("backsvr::openapi_appkey", "140a6d51d67c477e83cd91a241678824")
	openapiSecret = beego.AppConfig.DefaultString("backsvr::openapi_secret", "88366f9fad954828a194f3232a78a471")
}

// func main() {
// 	info := IPLocation("119.185.149.47")
// 	fmt.Println(info)
// }
